package com.shfl.rect;

import com.shfl.stock.Stock;
import com.shfl.utils.PropertiesUtil;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RectD extends JFrame {

    private static final long serialVersionUID = 1L;

    int orgx, orgy, endx, endy;
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    BufferedImage image;
    BufferedImage tempImage;
    BufferedImage saveImage;
    Graphics g;


    private InputStream results;

    private Integer resultsCount;


    public Integer getResultsCount() {
        return resultsCount;
    }

    public void setResultsCount(Integer resultsCount) {
        this.resultsCount = resultsCount;
    }

    public InputStream getResults() {
        return results;
    }

    public void setResults(InputStream results) {
        this.results = results;
    }

    @Override
    public void paint(Graphics g) {
        //缩放因子和偏移量
        RescaleOp ro = new RescaleOp(0.8f, 0, null);
        tempImage = ro.filter(image, null);
        g.drawImage(tempImage, 0, 0, this);
    }

    public RectD() {
        resultsCount = 0;
        snapshot();
        setVisible(true);
        setDefaultLookAndFeelDecorated(false);
        try {
            ImageIcon icon=new ImageIcon(getClass().getResource(PropertiesUtil.getProperty(Stock.proUrl, "project.icons")));
            setIconImage(icon.getImage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //setSize(d);//最大化窗口
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                orgx = e.getX();
                orgy = e.getY();
            }
        });
        //鼠标运动监听器
        this.addMouseMotionListener(new MouseMotionAdapter() {
            //鼠标拖拽事件
            public void mouseDragged(MouseEvent e) {
                endx = e.getX();
                endy = e.getY();
                g = getGraphics();
                g.drawImage(tempImage, 0, 0, RectD.this);
                int x = Math.min(orgx, endx);
                int y = Math.min(orgy, endy);
                //加上1，防止width,height为0
                int width = Math.abs(endx - orgx) + 1;
                int height = Math.abs(endy - orgy) + 1;
                g.setColor(Color.BLUE);
                g.drawRect(x - 1, y - 1, width + 1, height + 1);
                //减1，加1都是为了防止图片将矩形框覆盖掉
                saveImage = image.getSubimage(x, y, width, height);
                g.drawImage(saveImage, x, y, RectD.this);
            }
        });
        //鼠标点击事件
        this.addMouseListener(new MouseListener() {
                                  @Override
                                  public void mouseClicked(MouseEvent e) {
                                      if (e.getClickCount() == 2) {
                                          try {
                                              dispose();
                                              Stock.rd.setResults(getImageIo());
                                              synchronized (Stock.obj) {
                                                  Stock.obj.notify();
                                              }
                                          } catch (Exception e1) {
                                              e1.printStackTrace();
                                              throw new RuntimeException(e1.getMessage());
                                          } finally {
                                              dispose();
                                          }
                                      }
                                  }

                                  @Override
                                  public void mousePressed(MouseEvent e) {

                                  }

                                  @Override
                                  public void mouseReleased(MouseEvent e) {

                                  }

                                  @Override
                                  public void mouseEntered(MouseEvent e) {

                                  }

                                  @Override
                                  public void mouseExited(MouseEvent e) {

                                  }
                              }

        );

        //监听案件
        this.addKeyListener(new KeyAdapter() {
            @Override
            //按键释放
            public void keyReleased(KeyEvent e) {
                System.out.print(e.getKeyCode());
                //按Esc键退出
                if (e.getKeyCode() == 27 || e.getKeyCode() == 10) {
                    try {
                        dispose();
                        Stock.rd.setResults(getImageIo());
                        synchronized (Stock.obj) {
                            Stock.obj.notify();
                        }
                    } catch (Exception e1) {
                        throw new RuntimeException(e1.getMessage());
                    } finally {
                        dispose();
                    }
                }
            }
        });
    }

    public void saveToFile() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
        String name = sdf.format(new Date());
        File path = FileSystemView.getFileSystemView().getHomeDirectory();
        String format = "jpg";
        //  System.out.print(path+File.separator+name+"."+format);
        File f = new File(path + File.separator + name + "." + format);
        try {
            ImageIO.write(saveImage, format, f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public InputStream getImageIo() {
        if(saveImage!=null){

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                ImageIO.write(saveImage, "png", os);
                InputStream input = new ByteArrayInputStream(os.toByteArray());
                return input;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    public String getImageStr() {
        InputStream in;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        byte[] data = null;
        // 读取图片字节数组
        try {
            ImageIO.write(saveImage, "png", baos);
            //in = new FileInputStream("");
            data = baos.toByteArray();
//            in.read(data);
//            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //System.out.print(URLEncoder.encode(encoder.encode(data)));
        // 返回Base64编码过再URLEncode的字节数组字符串
        return URLEncoder.encode(encoder.encode(data));
    }

    public void snapshot() {

        try {
            Robot robot = new Robot();
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            image = robot.createScreenCapture(new Rectangle(0, 0, d.width, d.height));

        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        //全屏运行
//        RectD rd = new RectD();
//        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
//                .getDefaultScreenDevice();
//        gd.setFullScreenWindow(rd);
//        rd.getDefaultCloseOperation();
//
//    }

}

